<?php

require_once dirname(dirname(__FILE__)) . '/config/config.php';
require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'db_connection.php';
require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php';

class dao_user {

    public function login($user, $pass) {
        $db = new db_connection();
        $con = $db->open_connect();

        $query = "SELECT * FROM tbladmin WHERE Name = '" . $user . "' AND Password = '" . md5($pass) . "'";
        $result = mysqli_query($con, $query);
        if (!$result) {
            printf("Error: %s\n", mysqli_error($con));
            exit();
        }
        if (mysqli_fetch_array($result) != FALSE) {
            $db->close_connect($con);
            return TRUE;
        } else {
            $db->close_connect($con);
            return FALSE;
        }
    }

    public function logout() {
        session_start();
        $_SESSION['user'] = '';
        lib_redirect::Redirect(DIR_ADMIN . 'index.php');
    }

    public function get_admin_password() {
        $db = new db_connection();
        $con = $db->open_connect();
        
        $new_pass = rand(101010, 999999);
        
        $query = "UPDATE tbladmin SET Password = '" . md5($new_pass) . "' WHERE name = 'admin'";
        mysqli_query($con, $query) or die('Query Failed: ' . mysqli_error());
        
        if(mail('mshahbaz@tesdo.org', 'Tesdo Password Recover', 'Your password is: ' . $new_pass)){
            $db->close_connect($con);
            return true;
        } else {
            $db->close_connect($con);
            return false;
        }
    }

    public function set_admin_password($pass) {
        $db = new db_connection();
        $con = $db->open_connect();

        
        $query = "UPDATE tbladmin SET Password = '" . md5($pass) . "' WHERE Name = 'admin'";
        if(mysqli_query($con, $query)){
            $db->close_connect($con);
            return true;
        } else {
            $db->close_connect($con);
            return false;
        }
    }
}
